//
//  AuthenItemView.swift
//  EasyDana
//
//  Created by mac on 2024/10/15.
//

import UIKit
import RxSwift
import RxCocoa
struct AuthenItemModel: Codable {
    
    struct ItemEnumModel: Codable {
        let th: String
        let cordially: String
        
        init(from decoder: any Decoder) throws {
            let container: KeyedDecodingContainer<AuthenItemModel.ItemEnumModel.CodingKeys> = try decoder.container(keyedBy: AuthenItemModel.ItemEnumModel.CodingKeys.self)
            self.th = try container.decode(String.self, forKey: AuthenItemModel.ItemEnumModel.CodingKeys.th)
            do {
                self.cordially = try container.decode(String.self, forKey: AuthenItemModel.ItemEnumModel.CodingKeys.cordially)
            } catch {
                let cordially = try container.decode(Int.self, forKey: AuthenItemModel.ItemEnumModel.CodingKeys.cordially)
                self.cordially = String(cordially)
            }
        }
    }
    
    let genteel: Int?
    let convoys: String //标题
    let entail: String //提示
    let tombs: String
    let openly: String //上传的键值
    let pompeii: [ItemEnumModel] //选项列表
    var foolishly: String //回显值//可以更改
    var cordially: String? //回显key
    let graveyard: Int? //=1使用数字键盘
    
    init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.genteel = try container.decodeIfPresent(Int.self, forKey: .genteel)
        
        self.convoys = try container.decode(String.self, forKey: .convoys)
        self.entail = try container.decode(String.self, forKey: .entail)
        self.tombs = try container.decode(String.self, forKey: .tombs)
        self.openly = try container.decode(String.self, forKey: .openly)
        self.pompeii = try container.decode([AuthenItemModel.ItemEnumModel].self, forKey: .pompeii)
        self.foolishly = try container.decode(String.self, forKey: .foolishly)
        do {
            self.cordially = try container.decodeIfPresent(String.self, forKey: .cordially)
        } catch {
            let cordially = try container.decodeIfPresent(Int.self, forKey: .cordially)
            if let c = cordially {
                self.cordially = "\(c)"
            }
        }
        self.graveyard = try container.decodeIfPresent(Int.self, forKey: .graveyard)
    }
}

class AuthenItemView: UIView {

    private let bag = DisposeBag()
    let model: BehaviorRelay<AuthenItemModel>
    
    var areas: [AreaModel?] = []
    
    init(model: BehaviorRelay<AuthenItemModel>) {
        self.model = model
        super.init(frame: CGRect.zero)
        self.configView()
    }
    
    private func configView() {
        self.backgroundColor = UIColor.white
        let titleLabel = UILabel()
        self.addSubview(titleLabel)
        titleLabel.textColor = UIColor.hex(with: "666666")
        titleLabel.font = UIFont.systemFont(ofSize: 14)
        self.model.map({$0.convoys}).bind(to: titleLabel.rx.text).disposed(by: self.bag)
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(15)
        }
        switch self.model.value.tombs {
        case "dead":
            //选择
            let field = UITextField()
            self.addSubview(field)
            field.textColor = UIColor.hex(with: "121011")
            field.font = UIFont.systemFont(ofSize: 16, weight: .medium)
            field.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(15)
                make.height.equalTo(16)
            }
            self.model.map({$0.foolishly}).bind(to: field.rx.text).disposed(by: self.bag)
            self.model.map { m in
                return m.graveyard == 1 ? UIKeyboardType.numberPad : UIKeyboardType.default
            }
            .bind(to: field.rx.keyboardType)
            .disposed(by: self.bag)
            self.model.map({$0.entail}).bind(to: field.rx.placeholder).disposed(by: self.bag)
            field.rightViewMode = .always
            field.rightView = UIImageView(image: UIImage(named: "authen_enter"))
            field.rightView?.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 20, height: 20))
            let button = UIButton(type: .system)
            self.addSubview(button)
            button.snp.makeConstraints { make in
                make.edges.equalTo(self)
            }
            button.rx.tap
                .subscribe(onNext: { [weak self] event in
                    let vc = EnumViewController()
                    vc.source = self!.model.value.pompeii
                    vc.name = self!.model.value.entail
                    if self!.model.value.cordially?.count ?? 0 > 0 {
                        let m = self!.model.value.pompeii.filter({"\($0.cordially)" == self!.model.value.cordially}).first
                        vc.currentModel.accept(m)
                    }
                    vc.confirm
                        .filter({$0 != nil})
                        .withLatestFrom(self!.model, resultSelector: { itemModel, mod in
                            var m = mod
                            m.foolishly = itemModel!.th
                            m.cordially = "\(itemModel!.cordially)"
                            return m
                        })
                        .bind(to: self!.model)
                        .disposed(by: self!.bag)
                    UIViewController.top?.alert(viewController: vc)
                })
                .disposed(by: self.bag)
            break
        case "most":
            //输入框
            let field = UITextField()
            self.addSubview(field)
            field.textColor = UIColor.hex(with: "121011")
            field.font = UIFont.systemFont(ofSize: 16, weight: .medium)
            field.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(15)
                make.height.equalTo(16)
            }
            self.model.map({$0.foolishly}).bind(to: field.rx.text).disposed(by: self.bag)
            self.model.map { m in
                return m.graveyard == 1 ? UIKeyboardType.numberPad : UIKeyboardType.default
            }
            .bind(to: field.rx.keyboardType)
            .disposed(by: self.bag)
            self.model.map({$0.entail}).bind(to: field.rx.placeholder).disposed(by: self.bag)
            field.rx.text.orEmpty
                .withLatestFrom(model) { text, currentValue in
                    var updatedValue = currentValue
                    updatedValue.foolishly = text
                    return updatedValue
                }
                .bind(to: model)
                .disposed(by: self.bag)
            break
        case "best":
            //城市选择
            let field = UITextField()
            self.addSubview(field)
            field.textColor = UIColor.hex(with: "121011")
            field.font = UIFont.systemFont(ofSize: 16, weight: .medium)
            field.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(15)
                make.height.equalTo(16)
            }
            self.model.map({$0.foolishly}).bind(to: field.rx.text).disposed(by: self.bag)
            self.model.map { m in
                return m.graveyard == 1 ? UIKeyboardType.numberPad : UIKeyboardType.default
            }
            .bind(to: field.rx.keyboardType)
            .disposed(by: self.bag)
            self.model.map({$0.entail}).bind(to: field.rx.placeholder).disposed(by: self.bag)
            field.rightViewMode = .always
            field.rightView = UIImageView(image: UIImage(named: "authen_enter"))
            field.rightView?.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 20, height: 20))
            let button = UIButton(type: .system)
            self.addSubview(button)
            button.snp.makeConstraints { make in
                make.edges.equalTo(self)
            }
            button.rx.tap
                .subscribe(onNext: { [weak self] event in
                    let vc = CitiesViewController()
                    vc.choosenAreas = self?.areas ?? []
                    vc.confirmArea.withLatestFrom(self!.model) { areas, model in
                        var m = model
                        let a = areas.filter({($0?.th.count ?? 0) > 0})
                            .map({$0?.th ?? ""})
                            .joined(separator: "|")
                        self?.areas = areas
                        m.foolishly = a
                        return m
                    }
                    .bind(to: self!.model)
                    .disposed(by: self!.bag)
                    UIViewController.top?.alert(viewController: vc)
                })
                .disposed(by: self.bag)
            break
        default:
            break
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
